package per.com.service.ServiceImpl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import per.com.bean.Comment;
import per.com.bean.User;
import per.com.common.ServerResponse;
import per.com.dao.CommentMapper;
import per.com.dao.PcUsersDao;
import per.com.service.ICommentService;
import per.com.utils.DateTimeUtil;
import per.com.vo.CommentDetailVo;

/**
 * @author zxy
 */
@Service("iCommentService")
public class CommentServiceImpl implements ICommentService {

    @Autowired
    private CommentMapper commentMapper;

    @Autowired
    private PcUsersDao pcUsersDao;

    @Override
    public ServerResponse<CommentDetailVo> addComment(Comment comment) {

        int resultCount = commentMapper.insert(comment);
        if (resultCount > 0){
            Comment comment1 = commentMapper.selectByPrimaryKey(comment.getId());
            CommentDetailVo commentDetailVo = assembleCommentDetailVo(comment1);
            return ServerResponse.createBySuccess(commentDetailVo);
        }

        return ServerResponse.createByErrorMessage("评论失败");
    }

    @Override
    public ServerResponse<CommentDetailVo> selectComment(String id) {

        Comment comment = commentMapper.selectByPrimaryKey(id);
        if (comment != null){
            CommentDetailVo commentDetailVo = assembleCommentDetailVo(comment);
            return ServerResponse.createBySuccess(commentDetailVo);
        }
        return ServerResponse.createByErrorMessage("查看评论失败");
    }

    private CommentDetailVo assembleCommentDetailVo(Comment comment){

        CommentDetailVo commentDetailVo = new CommentDetailVo();
        commentDetailVo.setId(comment.getId());
        commentDetailVo.setComment(comment.getComment());
        commentDetailVo.setUserId(comment.getUserId());
        commentDetailVo.setCommentedId(comment.getCommentedId());
        commentDetailVo.setCreateTime(DateTimeUtil.dateToStr(comment.getCreateTime()));
        commentDetailVo.setUpdateTime(DateTimeUtil.dateToStr(comment.getUpdateTime()));
        User user = pcUsersDao.selectByPrimaryKey(comment.getUserId());
        User commentedUser = pcUsersDao.selectByPrimaryKey(comment.getCommentedId());
        commentDetailVo.setUsername(user.getUsername());
        commentDetailVo.setCommentedUsername(commentedUser.getUsername());

        return commentDetailVo;
    }
}
